package ee.videorental.serverside;

import java.io.IOException;
import java.io.ObjectOutputStream;

import ee.videorental.Message;

public class BroadCaster extends Thread 
{
	private ObjectOutputStream netOut;
	private OutboundMessages outboundMessages;
	private volatile boolean thisThreadNotToBeKilled = true;

	
	public BroadCaster(OutboundMessages outboundMessages, ObjectOutputStream netOut, int clientSessionUID) 
	{
		this.netOut = netOut; 
		this.outboundMessages = outboundMessages;
		this.setName("ClientSessionBroadcasterThread-" + Integer.toString(clientSessionUID)); 
		start();
	}

	public void run() 
	{
		while (thisThreadNotToBeKilled)
		{
			Message messageToClient = outboundMessages.getMessage();
			
			try 
			{
				netOut.writeObject(messageToClient);
				netOut.reset();
			} 
			catch (IOException e) 
			{
				System.err.println("ERROR: while serializing message to client!");
			} 
		}
		
		tryToCloseObjectOutputStream();
	}
	
	private void tryToCloseObjectOutputStream()
	{
		try 
		{
			netOut.close(); 
			System.out.println("ObjectOutputStream netOut is being closed"); 
		}
		catch (Exception e) 
		{
			System.err.println("ERROR: while closing ObjectOutputStream!");
		}
	}
	
	public void setIsBroadCasterThreadNotToBeKilled(boolean isNotToBeKilled)
	{
		this.thisThreadNotToBeKilled = isNotToBeKilled; 
	}
}